﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace MyJoystic
{
    public class Joystic : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler
    {
        public static Joystic instance;
        private void Awake()
        {
            instance = this;
        }

        private RectTransform circleRtf;//内部圆的transfrom
        private bool draging = false;

        public Vector3 Value
        {
            get
            {
                Vector3 pos = circleRtf.localPosition;
                Vector3 dir = new Vector3(pos.x, 0, pos.y);
                float p = dir.magnitude / 70;
                dir = Vector3.Normalize(dir) * p;
                return dir;
            }
        }
        private void Start()
        {
            circleRtf = transform.Find("Circle") as RectTransform;
        }

        public void OnBeginDrag(PointerEventData eventData)
        {
            draging = true;
        }

        public void OnDrag(PointerEventData eventData)
        {
            Vector3 offset = Vector2.ClampMagnitude(((Vector3)eventData.position - transform.position), 70);
            circleRtf.position = transform.position + offset;
        }

        public void OnEndDrag(PointerEventData eventData)
        {
            draging = false;
        }

        private void Update()
        {
            if (!draging)
            {
                circleRtf.localPosition = Vector3.Lerp(circleRtf.localPosition, Vector3.zero, Time.deltaTime * 10f);
            }
        }
    }
}